import sys
from PyQt5.QtWidgets import QApplication,QWidget
from PyQt5 import QtWidgets
from PyQt5.QtCore import QStringListModel
import os
from serverui import Ui_Server
from LLone import grammar
import socket

class MainWidgets(QWidget,Ui_Server):

    mygrammar = None
    mysocket = None
    conn,addr = None,None
    matchSTR = ''


    def initSocket(self):
        HOST = '127.0.0.1'  # Symbolic name meaning all available interfaces
        PORT = 8881  # Arbitrary non-privileged port
        self.mysocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.textEdit.setText('Socket created')
        try:
            self.mysocket.bind((HOST, PORT))
        except socket.error:
            self.textEdit.setText('Bind failed')
            sys.exit()
        self.textEdit.setText('Socket bind complete')
        self.mysocket.listen(10)
        self.textEdit.append('Listening')

    def __init__(self):
        super(MainWidgets, self).__init__()
        self.setupUi(self)

        self.DORECEIVE.clicked.connect(self.receiveClicked)
        self.DOSEND.clicked.connect(self.sendClicked)
        #消除直接左递归
        self.EDLR.clicked.connect(self.EDLRClicked)
        self.EDILR.clicked.connect(self.EIDLRClicked)
        self.JUDGELLONE.clicked.connect(self.JUDGELLONEClicked)
        self.EXTRACT.clicked.connect(self.extractClicked)
        self.DOFIRST.clicked.connect(self.DOFIRSTClicked)
        self.DOFOLLOW.clicked.connect(self.DOFOLLOWClicked)
        self.DOSELECT.clicked.connect(self.DOSELECTClicked)
        self.ANALYSIS.clicked.connect(self.DOANALYSISClicked)
        self.Waiting.clicked.connect(self.WaitMessage)
        self.PRINT.clicked.connect(self.PRINTClicked)
        self.initSocket()

    def EDLRClicked(self):
        self.mygrammar.EDLR_ALL()
        self.OUTPUTWAITSENT.setText(self.mygrammar.formatgrammar())

    def EIDLRClicked(self):
        self.mygrammar.EIDLR()
        self.OUTPUTWAITSENT.setText(self.mygrammar.formatgrammar())

    def extractClicked(self):
        self.mygrammar.extract()
        self.OUTPUTWAITSENT.setText(self.mygrammar.formatgrammar())

    def DOFIRSTClicked(self):
        self.OUTPUTWAITSENT.setText(self.mygrammar.formatSet(first=True))

    def DOFOLLOWClicked(self):
        self.OUTPUTWAITSENT.setText(self.mygrammar.formatSet(follow=True))

    def DOSELECTClicked(self):
        self.OUTPUTWAITSENT.setText(self.mygrammar.formatSet(select=True))

    def PRINTClicked(self):
        self.mygrammar.DOFISRT()
        self.mygrammar.DOFOLLOW()
        self.mygrammar.DOSELECT()
        table = self.mygrammar.PredictAnalysis(self.matchSTR)
        ans = ''
        if table[1]:
            for i in table[0]:
               ans += i
               ans += '\n'
        self.OUTPUTWAITSENT.setText(ans)

    def DOANALYSISClicked(self):
        self.OUTPUTWAITSENT.setText(self.mygrammar.formatSet(analysis=True))

    def JUDGELLONEClicked(self):
        self.mygrammar.DOFISRT()
        self.mygrammar.DOFOLLOW()
        self.mygrammar.DOSELECT()
        if not self.mygrammar.judge_LLOne():
            self.OUTPUTWAITSENT.setText('NOT LL1')
        else:
            self.OUTPUTWAITSENT.setText('IT IS LL1')

    def WaitMessage(self):
        self.conn, self.addr = self.mysocket.accept()
        self.textEdit.append('Connected with ' + self.addr[0] + ':' + str(self.addr[1]))

    def receiveClicked(self):
        data = self.conn.recv(1024).decode('utf-8')
        l = data.split('\n')
        Nsym = set(l[0][3:].split(' '))
        Tsym = set(l[1][3:].split(' '))
        S = l[2][2]
        P = l[3][2:]
        print(l)
        self.matchSTR = l[4]
        self.mygrammar = None
        self.mygrammar = grammar(Tsym,Nsym,S,P)
        self.RECEIVEINPUT.setText(data)

    def sendClicked(self):
        self.conn.sendall(self.OUTPUTWAITSENT.toPlainText().encode("utf-8"))
        self.conn.close()
        self.mysocket.close()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = MainWidgets()
    w.show()

    sys.exit(app.exec_())